package com.ilop.sthome.ui.activity.device;

import android.content.Intent;
import androidx.recyclerview.widget.GridLayoutManager;
import android.util.Log;
import android.view.View;

import com.ilop.sthome.ui.activity.main.ContainLoginActivity;
import com.example.common.utils.LiveDataBus;
import com.ilop.sthome.common.CommonId;
import com.ilop.sthome.common.command.SiterCommand;
import com.ilop.sthome.data.event.EventAnswerOK;
import com.ilop.sthome.data.event.EventGatewayInfo;
import com.ilop.sthome.data.event.EventRefreshDevice;
import com.ilop.sthome.data.event.EventSynchronization;
import com.ilop.sthome.data.greenDao.DeviceInfoBean;
import com.ilop.sthome.mvp.contract.device.GatewayContract;
import com.ilop.sthome.mvp.present.device.GatewayPresenter;
import com.ilop.sthome.ui.activity.config.ProductActivity;
import com.ilop.sthome.ui.activity.main.MainActivity;
import com.ilop.sthome.ui.activity.scene.ChangeSceneActivity;
import com.ilop.sthome.ui.adapter.device.DeviceChildAdapter;
import com.siterwell.familywellplus.R;
import com.siterwell.familywellplus.databinding.ActivityGatewayMainBinding;

import java.util.List;

/**
 * @author skygge
 * @date 2019/9/27.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：网关主页
 */

public class GatewayMainActivity extends ContainLoginActivity<GatewayPresenter, ActivityGatewayMainBinding> implements DeviceChildAdapter.subDeviceCallBack, GatewayContract.IView {

    private String mDeviceName;
    private boolean mEntrance;
    private DeviceChildAdapter mChildAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_gateway_main;
    }

    @Override
    protected void initialize() {
        super.initialize();
        mDeviceName = getIntent().getStringExtra(CommonId.KEY_DEVICE_NAME);
        mEntrance = getIntent().getBooleanExtra(CommonId.KEY_ADD_NEW, false);
    }

    @Override
    protected void initPresent() {
        super.initPresent();
        mPresent = new GatewayPresenter(this, mDeviceName);
    }

    @Override
    protected void initView() {
        super.initView();
        mChildAdapter = new DeviceChildAdapter(mContext);
        mChildAdapter.setCallBack(this);
        mDBind.gatewaySubDevice.setLayoutManager(new GridLayoutManager(mContext, 2));
        mDBind.gatewaySubDevice.setAdapter(mChildAdapter);
    }

    @Override
    protected void initData() {
        super.initData();
        if (mEntrance) {
            mPresent.startSynchronization();
        }
    }

    @Override
    protected void initListener() {
        super.initListener();
        mDBind.ivGatewayBack.setOnClickListener(view -> finishActivity());
        mDBind.gatewayOperation.setOnClickListener(v -> mPresent.gatewayTextAlarm());
        mDBind.gatewaySilence.setOnClickListener(v -> mPresent.gatewayMute());
        mDBind.tabHistory.setOnClickListener(view -> {
            Intent intent = new Intent(this, GatewayHistoryActivity.class);
            intent.putExtra(CommonId.KEY_DEVICE_NAME, mDeviceName);
            startActivity(intent);
        });
        mDBind.tabDetails.setOnClickListener(view -> {
            Intent intent = new Intent(this, DeviceDetailActivity.class);
            intent.putExtra(CommonId.KEY_DEVICE_NAME, mDeviceName);
            startActivity(intent);
        });
        mDBind.tabSetting.setOnClickListener(view -> {
            Intent intent = new Intent(this, DeviceSettingActivity.class);
            intent.putExtra(CommonId.KEY_DEVICE_NAME, mDeviceName);
            startActivity(intent);
        });
        mDBind.gatewaySubAdd.setOnClickListener(() -> {
            Intent intent = new Intent(this, ProductActivity.class);
            intent.putExtra(CommonId.KEY_SUB_DEVICE,true);
            intent.putExtra(CommonId.KEY_DEVICE_NAME, mDeviceName);
            startActivity(intent);
        });
        mDBind.stateModelChange.setOnClickListener(view -> {
            Intent intent = new Intent(this, ChangeSceneActivity.class);
            intent.putExtra(CommonId.KEY_DEVICE_NAME, mDeviceName);
            startActivity(intent);
        });
        mDBind.gatewayRefresh.setOnRefreshListener(() -> {
            mPresent.startSynchronization();
            mDBind.gatewayRefresh.setRefreshing(false);
        });
    }

    @Override
    protected void initDataBus() {
        super.initDataBus();
        LiveDataBus.get().with(CommonId.KEY_EVENT_REFRESH_DEVICE, EventRefreshDevice.class).observe(this, event -> {
            if (event!=null){
                Log.i(TAG, "onEventMainThread: subDevice " +  event.getDevice_status());
                if (mDeviceName.equals(event.getDeviceName())) {
                    mPresent.findAllSubDevice();
                }
            }
        });

        LiveDataBus.get().with(CommonId.KEY_EVENT_GATEWAY_INFO, EventGatewayInfo.class).observe(this, event -> {
            if (event!=null){
                Log.i(TAG, "onEventMainThread: gateway" + event.getData_str2());
                String roomId = event.getData_str2().substring(0, 2);
                mPresent.getGatewayRoom(roomId);
            }
        });

        LiveDataBus.get().with(CommonId.KEY_EVENT_SYNCHRONIZATION, EventSynchronization.class).observe(this, event -> {
            if (event!=null){
                Log.i(TAG, "onEventMainThread: synchronization" + event.getState());
                if (event.getState() == EventSynchronization.SYN_DEVICE){
                    mPresent.synchronizationNickName(event.getDeviceName());
                }else if (event.getState() == EventSynchronization.SYN_FINISH){
                    mPresent.synchronizationGatewayRoom(event.getDeviceName());
                }
                mPresent.findAllSubDevice();
            }
        });

        LiveDataBus.get().with(CommonId.KEY_ANSWER_OK, EventAnswerOK.class).observe(this, event -> {
            if (event!=null){
                Log.i(TAG, "initDataBus: answerOK");
                if (event.getData_str1().length() == 9) {
                    int cmd = Integer.parseInt(event.getData_str1().substring(0, 4), 16);
                    if (cmd == SiterCommand.EQUIPMENT_CONTROL) {
                        if (CommonId.KEY_SUCCESS.equals(event.getData_str2())) {
                            mPresent.getGatewayResponse();
                        }
                    }
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresent.getDeviceState();
        mPresent.findAllSubDevice();
    }

    @Override
    public void onClick(DeviceInfoBean device) {
        mPresent.clickItem(device);
    }

    @Override
    public void refreshSubList(List<DeviceInfoBean> deviceList, boolean isShare) {
        mChildAdapter.setList(deviceList);
        mDBind.gatewaySubAdd.setVisibility(isShare ? View.GONE : View.VISIBLE);
        mDBind.gatewayEmpty.setVisibility(View.GONE);
    }

    @Override
    public void refreshNoList(boolean isShare) {
        mChildAdapter.setList(null);
        mDBind.gatewaySubAdd.setVisibility(View.GONE);
        mDBind.gatewayEmpty.setVisibility(isShare ? View.GONE : View.VISIBLE);
        if (!isShare) {
            mDBind.gatewayEmptyAdd.setOnClickListener(v -> {
                Intent intent = new Intent(this, ProductActivity.class);
                intent.putExtra(CommonId.KEY_SUB_DEVICE, true);
                intent.putExtra(CommonId.KEY_DEVICE_NAME, mDeviceName);
                startActivity(intent);
            });
        }else {
            mDBind.gatewayEmptyAdd.setImageResource(R.mipmap.scene_empty);
            mDBind.gatewayEmptyMsg.setText(getString(R.string.gateway_under_no_device));
        }
    }

    @Override
    public void skipActivity(Intent intent) {
        startActivity(intent);
    }

    @Override
    public void refreshState(String name, int state, String mode, boolean isShared) {
        mDBind.title.setText(name);
        mDBind.titleSceneMode.setText(state == 1 ? getString(R.string.on_line) : getString(R.string.off_line));
        mDBind.modelColor.setBackgroundResource(state == 1 ? R.drawable.device_status_normal : R.drawable.device_status_off_line);
        mDBind.stateModel.setText(mode);
        mDBind.gatewaySubAdd.setVisibility(isShared ? View.GONE : View.VISIBLE);
    }

    @Override
    public void showToastMsg(String msg) {
        showToast(msg);
    }

    private void finishActivity(){
        if (mEntrance){
            Intent intent = new Intent(mContext, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
        }else {
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        finishActivity();
    }
}
